<template>
  <el-dialog v-dialogDrag v-if="popenevTVisible" :title="modalTitle" :visible.sync="popenevTVisible" width="320px" :before-close="handleCancel" :close-on-click-modal="false">
    <!-- 搜索框 -->
    <el-input placeholder="搜索" v-model="searchkey">
      <i slot="prefix" class="el-input__icon el-icon-search hc"></i>
    </el-input>
    <el-scrollbar class="scorll-Y">
      <el-tree class="filter-tree mt-10" :data="treeData" :props="defaultProps" :node-key="replaceFields.value" :default-expand-all="defaultExpandAll" :check-strictly="checkStrictly" :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true" :default-expanded-keys="expandKeys" :show-checkbox="true" @check-change="onSelect" :filter-node-method="filterNode" ref="tree">
        <span @click.stop="handleTreeLable(node,data)" class="custom-tree-node" slot-scope="{ node,data }">
          <span>{{ node.label }}</span>
          <span style="padding-right: 10px">
          <el-button
            type="text"
            size="mini"
            v-if="node.childNodes.length > 0 && multiple && showAllSelect"
            @click.stop="() => handleAll(node, data)">
            <span>{{ data.allChecked ? '取消' : '全选' }}</span>
          </el-button>
        </span>
        </span>
      </el-tree>
    </el-scrollbar>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleOk">确定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import
{
  getCompanyTree
} from "../../api/module/systemOrg/systemOrg.js";
import PinYinMatch from "pinyin-match";
export default {
  data()
  {
    return {
      allSelectTree: true,
      popenevTVisible: true,
      searchkey: null,
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      multiple: false,
      replaceFields: {
        label: "orgCommonname",
        value: "unid",
      },
      checkStrictly: false,
      expandKeys: [],
      defaultExpandAll: true,
      //promise 状态
      promiseStatus: null,
      //回显是否是全名
      isShowfullName: false,
      modalTitle: "请选择机构",
      checkOrgList: [],//选择机构的机构列表
      isAll: false,
      nodeId: "",
      // 是否显示全选按钮
      showAllSelect: window.HC_config.VUE_APP_SHOWALL_CHOSEORG || false
    };
  },
  computed: {
    defaultProps()
    {
      let tampObj = {};
      tampObj.label = this.replaceFields.title || this.replaceFields.label;
      return tampObj;
    },
  },
  watch: {
    searchkey(val)
    {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    getOrgTree()
    {
      getCompanyTree().then((res) =>
      {
        this.treeData = res.result;
        this.$nextTick(() =>
        {
          this.selectedKeys.forEach(pre_key =>
          {
            this.$refs.tree.setChecked(pre_key, true, false);
          })
        })
      });
    },
    filterNode(value, data)
    {
      if (!value) return true;
      return PinYinMatch.match(data[this.defaultProps.label], value);
    },
    show(showData, replaceFields, multiple, config)
    {
      config = config || {};
      this.defaultExpandAll =
        config.defaultExpandAll != undefined && config.defaultExpandAll != null
          ? config.defaultExpandAll
          : true; //默认展开所以节点
      this.expandKeys = config.expandKeys || [];
      if (this.expandKeys && this.expandKeys.length > 0)
      {
        this.defaultExpandAll = false;
      }
      this.multiple = multiple || false;
      if (this.multiple)
      {
        this.checkStrictly = false;
      }
      else
      {
        this.checkStrictly = true;
      }
      //在显示复选框的情况下，是否严格的遵循父子不互相关联的做法
      if(config.checkStrictly != undefined && config.checkStrictly != null)
      {
         this.checkStrictly = config.checkStrictly
      }
      if (this.multiple && this.showAllSelect)
      {
        this.checkStrictly = true
      }

      this.isShowfullName = config.isShowfullName || false;

      this.replaceFields = replaceFields || this.replaceFields;
      this.replaceFields.value = this.replaceFields.key ? this.replaceFields.key : this.replaceFields.value;
      this.replaceFields.label = this.replaceFields.title ? this.replaceFields.title : this.replaceFields.label;
      if (showData && showData.constructor == Array)
      {
        showData.forEach(item =>
        {
          this.selectedKeys.push(item.unid);
        })
      }

      this.treeData = config.treeList || [];
      if (!this.treeData || this.treeData.length == 0)
      {
        this.getOrgTree();
      }
      else
      {
        this.modalTitle = "请选择";
        //通过setChecked 方式 反显节点
        this.$nextTick(() =>
        {
          this.selectedKeys.forEach(pre_key =>
          {
            this.$refs.tree.setChecked(pre_key, true, false);
          })
        })
      }
      // 创建promise
      return new Promise((resolve, reject) =>
      {
        this.promiseStatus = {
          resolve,
          reject,
        };
      });
    },
    handleOk()
    {
      if (this.isShowfullName)
      {
        this.replaceFields.label = "orgFullname"
      }
      if (this.multiple)
      {
        // 获取已勾选数据
        var selectList = this.$refs.tree.getCheckedNodes()
        console.log(selectList, '确定')
        // 多选
        this.promiseStatus.resolve({
          choiceData: selectList,
          replaceFields: this.replaceFields,
        });
      } else
      {
        let selects = this.$refs.tree.getCheckedNodes();
        //单选
        this.promiseStatus.resolve({
          choiceData: selects,
          replaceFields: this.replaceFields,
        });
      }
      //清空勾选项
      this.selectedKeys = [];

      this.destroyElement();
    },
    // 父节点全选
    handleAll(P_Node,P_Data)
    {
      console.log("父节点全选");
      this.$set(P_Data,'allChecked',!P_Data.allChecked)
      
      this.checkChilrdNode(P_Data,P_Data.allChecked);
      this.nodeId = P_Data.unid
    },
    //递归选中
    checkChilrdNode(P_Data,P_Checked)
    {
         this.$refs.tree.setChecked(P_Data[this.replaceFields.value],P_Checked,P_Checked);
         if(P_Data.children && P_Data.children.length > 0)
         {
            P_Data.children.forEach(pre_item => {
              this.checkChilrdNode(pre_item,P_Checked)
            })
         }
    },
    //点击树的文字
    handleTreeLable(P_Node,P_Data)
    {
      console.log("----树文字-------", P_Node)
      if (P_Data.disabled)
      {
        return;
      }
      // console.log(P_Node.key);
      this.$refs.tree.setChecked(P_Node.key, !P_Node.checked, false);
    },
    //取消勾选
    handleCancel()
    {
      //清空勾选项
      this.promiseStatus.reject({
        msg: "取消",
      });
      this.selectedKeys = [];
      this.destroyElement();
    },
    //监听机构选择
    onSelect(data, check, tree)
    {
      console.log("----------勾选------------")
      console.log(data);
      console.log(check);
      console.log("----------勾选------------")
      //为了保存勾选顺序采用手动存储
      if (check)
      {
        //勾选
        this.checkOrgList.push(data);
      }
      else
      {
        //取消
        let findIndex = this.checkOrgList.findIndex(per_item =>
        {
          return per_item[this.replaceFields.value] == data[this.replaceFields.value];
        })
        if (findIndex >= 0)
        {
          this.checkOrgList.splice(findIndex, 1);
        }
      }

      if (check && !this.multiple)
      {
        this.$refs.tree.setCheckedKeys([data[this.replaceFields.value]]);
      }
    },
    /**
     * 监听搜索框改变
     */
    searchChange(e)
    {
      console.log(this.searchkey);
    },
    /**
     * cs 2022-4-8
     * 销毁组件
     */
    destroyElement()
    {
      this.popenevTVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.scorll-Y {
  height: 400px;
  margin-top: 10px;

  ::v-deep .el-scrollbar__wrap {
    overflow-x: auto;
  }
  ::v-deep .el-scrollbar__view {
    height: 100%;
  }
  ::v-deep .el-tree {
    height: 97%;
  }
}
.custom-tree-node {
  width: fit-content;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex: 1;
}
::v-deep .el-tree-node {
  // width: fit-content;
}
</style>
